package com.atguigu.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class OrderPayedListener {
    @Autowired OrderService orderService;
    @Autowired AlipayTemplate alipayTemplate;

    /**
     * 付款成功后，支付宝异步通知支付结果
     */
    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {
        System.out.println("收到支付宝的异步通知******************");
        //只要收到支付宝的异步通知，返回 success 支付宝便不再通知
        //TODO 需要验签
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();    //从请求中获取所有的请求参数
        for (String name : requestParams.keySet()) {    //requestParams.keySet()：获取密钥集名称
            String[] values = requestParams.get(name);    //根据 密钥集名称 到请求参数集合中获取参数
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //rsa 检查
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayTemplate.getAlipay_public_key(),   //支付宝公钥
                alipayTemplate.getCharset(),    //字符编码格式
                alipayTemplate.getSign_type());    //签名方式

        if (signVerified){
            System.out.println("支付宝异步通知验签成功");
            //修改订单状态
            String result = orderService.handlePayResult(vo);    //调用《处理支付成功返回的结果》方法
            return result;
        }else {
            System.out.println("支付宝异步通知验签失败");
            return "error";
        }}
}
